from flask import Blueprint,request
from model.model import *
from tools.tools import my_route,item2dict
facilit=Blueprint('/facilit',__name__)

@facilit.route('/facilit' ,methods=['get'])
def facilit_get():
    aa=facility.query.all()
    # temp=[]
    # for i in aa:
    #     temp.append({
    #         'id':i.id,
    #         'name':i.name,
    #         'house_id':i.house_id
    #     })
    return my_route(2000,item2dict(aa))



@facilit.route('/facilit' ,methods=['post'])
def facilit_add():
    params=request.json
    pid=params.pop('pid')
    aa=facility(**params)
    db.session.add(aa)
    db.session.commit()

    aa=facility.query.all()
    temp=[]
    for i in aa:
        temp.append({
            'id':i.id,
            'name':i.name,
            'house_id':i.house_id
        })
    return ({'code':200,'data':temp})


@facilit.route('/facilit' ,methods=['put'])
def facilit_put():
    params=request.json
    pid=params.pop('pid')
    facility.query.filter_by(id=pid).update({"name":params.get('name'),"house_id":params.get('house_id')})
    db.session.commit()
    aa=facility.query.all()
    temp=[]
    for i in aa:
        temp.append({
            'id':i.id,
            'name':i.name,
            'house_id':i.house_id
        })
    return ({'code':200,'data':temp})



@facilit.route('/facilit' ,methods=['delete'])
def facilit_delete():
    params=request.json
    pid=params.pop('pid')
    fa=facility.query.filter_by(id=pid).first()
    db.session.delete(fa)
    db.session.commit()

    return ({'code':204,})

